/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.partner.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.partner.domain.PartnerAccount;
import me.zhengjie.modules.partner.repository.PartnerAccountRepository;
import me.zhengjie.modules.partner.service.PartnerAccountService;
import me.zhengjie.modules.partner.service.dto.PartnerAccountDto;
import me.zhengjie.modules.partner.service.mapstruct.PartnerAccountMapper;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @website https://el-admin.vip
 * @description 服务实现
 * @author jianyongjie@126.com
 * @date 2021-08-05
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class PartnerAccountServiceImpl implements PartnerAccountService {

    private final PartnerAccountRepository partnerAccountRepository;
    private final PartnerAccountMapper partnerAccountMapper;

    /**
     * 检查账号是否存在（所有商户）
     * @param username
     * @return
     */
    private boolean isExists(String username) {
        final PartnerAccount exp = new PartnerAccount();
        exp.setUsername(username);

        return partnerAccountRepository.exists(Example.of(exp));
    }


    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void createAccount(Long partnerId, String username, String phone) {
        if (isExists(username)) {
            throw new BadRequestException("账号:" + username + "已存在，不能创建");
        }
        PartnerAccount partnerAccount = new PartnerAccount();
        partnerAccount.setId(IdWorker.getId());
        partnerAccount.setPartnerId(partnerId);
        partnerAccount.setUsername(username);
        partnerAccount.setPassword("123456");
        partnerAccount.setSalt(RandomUtil.randomString(6));
        partnerAccount.setSuperAdmin(Boolean.TRUE);
        partnerAccount.setEnable(Boolean.TRUE);
        partnerAccount.setName("系统管理员");
        partnerAccount.setSex(1);
        partnerAccount.setPhone(phone);
        partnerAccountRepository.save(partnerAccount);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateAccount(Long partnerId, String username, String phone) {
        PartnerAccount partnerAccount = partnerAccountRepository.findByPartnerIdAndSuperAdminTrue(partnerId);
        if (partnerAccount == null) {
            log.info("管理员账号不存在，创建 商户ID:{}, 账号名称:{}", partnerId, username);
            createAccount(partnerId, username, phone);
        } else {
            log.info("管理员账号已经存在，进行修改逻辑，商户ID:{}", partnerId);

            //检查待修改的账号是否存在(排除当前商户）
            final PartnerAccount byPartnerIdNotAndUsername = partnerAccountRepository.findByPartnerIdNotAndUsername(partnerId, username);
            if (byPartnerIdNotAndUsername == null) {
                partnerAccount.setUsername(username);
                partnerAccount.setPhone(phone);
                partnerAccountRepository.save(partnerAccount);
            } else {
                throw new BadRequestException("账号:" + username + "已存在，不能创建");
            }
        }
    }

    @Override
    public PartnerAccountDto findByAdminAccount(Long partnerId) {
        return partnerAccountMapper.toDto(partnerAccountRepository.findByPartnerIdAndSuperAdminTrue(partnerId));
    }

    @Override
    public List<PartnerAccountDto> findListByPartnerId(Long partnerId) {
        final PartnerAccount exp = new PartnerAccount();
        exp.setPartnerId(partnerId);
        final List<PartnerAccount> all = partnerAccountRepository.findAll(Example.of(exp));
        return partnerAccountMapper.toDto(all);
    }
}